package com.zhw.task;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 建立任务之间的关系(有向无环图)
 */
public class DAGProject {

    /**
     * 储存所有的任务
     */
    private final Set<IDAGTask> mTaskSet;
    /**
     * 储存所有的任务和前置依赖任务
     */
    private final Map<IDAGTask, Set<IDAGTask>> mTaskMap;

    public DAGProject(Builder builder) {
        mTaskSet = builder.mTaskSet;
        mTaskMap = builder.mTaskMap;
    }

    Set<IDAGTask> getDAGTaskSet() {
        return mTaskSet;
    }

    Map<IDAGTask, Set<IDAGTask>> getDAGTaskMap() {
        return mTaskMap;
    }

    public static class Builder {
        private final Set<IDAGTask> mTaskSet = new HashSet<>();
        private final Map<IDAGTask, Set<IDAGTask>> mTaskMap = new HashMap<>();

        public Builder addDAGTask(IDAGTask DAGTask) {
            if (this.mTaskSet.contains(DAGTask)) {
                throw new IllegalArgumentException();
            }
            this.mTaskSet.add(DAGTask);
            return this;
        }

        public Builder addDAGEdge(IDAGTask iDAGTask, IDAGTask preDAGTask) {
            if (!this.mTaskSet.contains(iDAGTask) || !this.mTaskSet.contains(preDAGTask)) {
                throw new IllegalArgumentException();
            }
            Set<IDAGTask> preDAGTaskSet = this.mTaskMap.computeIfAbsent(iDAGTask, k -> new HashSet<>());
            if (preDAGTaskSet.contains(preDAGTask)) {
                throw new IllegalArgumentException();
            }
            iDAGTask.addRely();
            preDAGTaskSet.add(preDAGTask);
            preDAGTask.addNextDAGTask(iDAGTask);
            return this;
        }

        public DAGProject builder() {
            return new DAGProject(this);
        }
    }

}
